package cn.ibizlab.extensions.ey;

import cn.ibizlab.util.helper.JacksonUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.Data;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Data
public class EYHeader {


    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = -2780973508045259108L;

    private Long userId;

    private String username;

    private String email;

    private Long aadUserId;

    private String systemId;

    /**
     * User-Agent
     */
    private String deviceInfo;

    /**
     * client端IP地址
     */
    private String clientIp;

    /**
     * 属性名：版本号
     */
    private String version;

    /**
     * token
     */
    private String token;


    public static String KEY_USERINFO_IN_HTTP_HEADER = "X-EY-HEADER";

    public static EYHeader getInstance()
    {
        EYHeader eyHeader = null;
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(requestAttributes!=null) {
                HttpServletRequest request = requestAttributes.getRequest();
                if(request!=null){
                    eyHeader = (EYHeader) request.getAttribute(KEY_USERINFO_IN_HTTP_HEADER);;
                    if(eyHeader == null) {
                        String eyUser  = request.getHeader(KEY_USERINFO_IN_HTTP_HEADER);
                        String userName = request.getHeader("userName");
                        if(eyUser != null) {
                            eyHeader= JacksonUtils.toObj(java.net.URLDecoder.decode(eyUser, "utf-8"), EYHeader.class);
                            if(eyHeader==null||eyHeader.getUsername()==null||eyHeader.getEmail()==null)
                                return null;
                            if(eyHeader.getUsername().indexOf("\"")>=0){
                                eyHeader.setUsername(eyHeader.getUsername().replace("\"",""));
                                eyHeader.setEmail(eyHeader.getEmail().replace("\"",""));
                            }
                        }
                        else if (!ObjectUtils.isEmpty(userName)) {
                            eyHeader=new EYHeader();
                            eyHeader.setUserId(IdWorker.getId());
                            eyHeader.setUsername(userName);
                            eyHeader.setEmail(userName);
                            eyHeader.setSystemId(request.getHeader("projectid"));
                        }
                    }
                }
            }
        }
        catch (Exception ex) {

        }
        return eyHeader;
    }


}
